package com.example.demo.controller;

import com.example.demo.entity.ParkingLot;
import com.example.demo.entity.PricingStandard;
import com.example.demo.service.ParkingLotService;
import com.example.demo.service.PricingStandardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
//自动识别跳转路径
@RequestMapping("/parking")
public class ParkingLotController {

    ParkingLotService service;
    PricingStandardService pricingStandardService;
    @Autowired
    public ParkingLotController(ParkingLotService service, PricingStandardService pricingStandardService){
        this.service=service;
        this.pricingStandardService=pricingStandardService;
    }

    @RequestMapping("/list")//和HTML文件对标
    public String list(Model model){
        //通过model传值到页面
        List<ParkingLot> entities=service.getAll();
        model.addAttribute("list",entities);//model打包成list属性完成List对象的值传递
        return "/parking/list";
    }

    @RequestMapping(value = "/insert")//跳转到edit页面
    public String insert(Model model){
        model.addAttribute("parking",new ParkingLot());
        List<PricingStandard> pricing=pricingStandardService.getAll();//获取停车场的所有数据
        model.addAttribute("pricing",pricing);
        return "/parking/edit";
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(@ModelAttribute("parking") ParkingLot entity, @RequestParam("pricingId") Long pricingId){//执行后提交到后端
        System.out.println(entity);
        PricingStandard pricing=pricingStandardService.getById(pricingId);
        entity.setPricingStandardId(pricingId);
        entity.setPricingStandard(pricing);
        boolean result=entity.getId()!=null ? service.update(entity):service.insert(entity);
        return "redirect:/parking/list";
    }


    @RequestMapping(value = "/detail/{id}")
    public String detail(@PathVariable("id")Long id,Model model){
        ParkingLot entity=service.getById(id);
        model.addAttribute("parking",entity);
        return "/parking/detail";
    }

    @RequestMapping(value = "/edit/{id}")
    public String entity(@PathVariable("id") Long id, Model model){
        ParkingLot entity=service.getById(id);
        model.addAttribute("parking",entity);
        List<PricingStandard> pricing=pricingStandardService.getAll();//获取停车场的所有数据
        model.addAttribute("pricing",pricing);
        return "/parking/edit";
    }


    @RequestMapping(value = "/delete/{id}")
    public String delete(@PathVariable("id")Long id){
        boolean entity=service.delete(id);
        return "redirect:/parking/list";
    }

}
